﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TorchView.Game;
using System.ComponentModel;
using TorchView.SharedStashEditor.ViewModels;

namespace TorchView.SharedStashEditor.Models
{
    public class ItemSlot<T> : INotifyPropertyChanged where T: struct, IComparable, IConvertible, IFormattable
    {
        private ItemViewModel _item;
        private string _name;

        public ItemSlot(T slot, Item item = null)
        {
            Slot = slot;
            setItem(item);
        }

        public bool HasItem
        {
            get
            {
                return (_item != null);
            }
        }

        public void setItem(Item item)
        {
            if (item == null)
            {
                _item = null;
                _name = String.Format("[{0}] <Empty>",Slot);
            }
            else
            {
                _item = new ItemViewModel(item);
                _item.PropertyChanged += new PropertyChangedEventHandler(ItemPropertyChanged);
                _name = String.Format("[{0}] {1}", Slot, _item.ToString());
            }

            NotifyPropertyChanged("Item");
        }

        private void ItemPropertyChanged(Object sender, PropertyChangedEventArgs e)
        {
            ItemViewModel itemVM = (ItemViewModel)sender;
            if (e.PropertyName.Equals("Name") ||
               e.PropertyName.Equals("Prefix") ||
               e.PropertyName.Equals("Suffix"))
            {
                _name = String.Format("[{0}] {1}", Slot, itemVM.ToString());
                NotifyPropertyChanged("Name");
            }
        }

        public ItemViewModel Item
        {
            get { return _item;  }
        }
        public T Slot { get; private set; }

        public uint UInt
        {
            get
            {
                if (typeof(T).IsEnum)
                    return Convert.ToUInt32(Slot);
                else
                    return 0;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }

        public override string ToString()
        {
            return _name;
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #endregion
    }
}
